import {messages} from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import { Button, Badge, message, Input, Icon } from 'antd'
import creditModelService from 'containers/credit-setting/credit-model/credit-model.service'
import NewCreditModelRule from 'containers/credit-setting/credit-model/credit-model-detail/new-credit-model-rule'
import SlideFrame from 'components/slide-frame'
import constants from 'share/constants'
import BasicInfo from 'components/basic-info'
import debounce from 'lodash.debounce'
const Search = Input.Search;
import errorMessage from 'share/errorMessage'
import menuRoute from 'routes/menuRoute'
import ResizeTable from 'components/resize-table';

class CreditModelRules extends React.Component{
  constructor(props) {
    super(props);
    this.setId = this.props.params.setId;
    this.state = {
      showSlideFrame: false,
      columns: [{
        title: messages('common.sequence')/*序号*/, dataIndex: 'index', width: 48
      },{
        title: messages('credit-setting.key100')/*规则项编码*/, dataIndex: 'ruleConditionCode', width: 100
      },{
        title: messages('credit-setting.key39')/*规则项*/, dataIndex: 'ruleCondition', width: 150
      },{
        title: messages('common.remark')/*备注*/, dataIndex: 'comment'
      },{
        title: messages('credit-setting.key109')/*关联对象*/, dataIndex: 'creditRelationDTOList', render:  (text, record) =>{
          if (record.creditRelationDTOList && !!record.creditRelationDTOList.length) {
            return record.creditRelationDTOList.map(item => item.reply).join()
          } else if (record.creditTaskDTOList && !!record.creditTaskDTOList.length) {
            return record.creditTaskDTOList.map(item => item.content).join('；')
          }
        }
      },{
        title: messages('credit-setting.key41')/*处理类型*/, dataIndex: 'operationType', render: operationType => constants.getTextByValue(operationType, 'creditRuleOperation'), width: 96
      },{
        title: messages('credit-setting.key42')/*结果*/, dataIndex: 'changeScore', width: 48, render: (text, record) =>
          `${record.operationType % 2 === 0 ? '-' : ''}${record.operationType > 1002 ? record.changeRank : record.changeScore}`
      },{
        title: messages('common.column.status')/*状态*/, dataIndex: 'valid', render: valid => (
          <Badge status={valid ? 'success' : 'error'}
                 text={valid ? messages("common.status.enable") : messages("common.status.disable")}/>
        ), width: 96
      }],
      pagination: {
        total: 0
      },
      searchParams: {
        ruleCondition: ''
      },
      page: 0,
      size: 10,
      data: [],
      nowData: {},
      rulesGroup: {},
      loading: false,
      infoList: [
        {type: 'input', id: 'ruleSetName',required: true, label: messages('credit-setting.key43')/*名称*/},
        {type: 'input', id: 'ruleTypeName',required: true, disabled: true, label: messages('credit-setting.key44')/*类型*/ },
        {type: 'input', id: 'comment',required: true, label: messages('common.remark')/*备注*/},
        {type: 'switch', id: 'valid', label: messages('common.column.status')/*状态*/}
      ],
      saving: false,
      updateState: false
    };
    this.handleSearch = debounce(this.handleSearch, 500);
  }

  handleBack = () => {
    const { creditModel } = this.props;
    this.context.router.push(menuRoute.getRouteItem('credit-model-detail').url.replace(':id', creditModel.id) + '?tab=rules')
  };

  componentWillMount(){
    this.getList();
    this.getData();
  }

  handleUpdateRulesGroup = result => {
    const { rulesGroup } = this.state;
    this.setState({ saving: true });
    creditModelService.saveCreditRulesGroup(Object.assign({}, rulesGroup, result)).then(res => {
      message.success(messages('credit-setting.key45')/*保存成功*/);
      this.setState({ updateState: true, saving: false });
      this.getData();
    }).catch(e => {
      errorMessage(e.response);
      this.setState({ updateState: false, saving: false });
    });
  };

  getData = () => {
    creditModelService.getCreditRulesGroup(this.setId).then(res => {
      let name = '';
      switch(res.data.ruleTypeId){
        case 1001:
          name = messages('credit-setting.key110')/*节点模式*/;
          break;
        case 1002:
          name = messages('credit-setting.key46')/*手动模式*/ ;
          break;
        case 1003:
          name = messages('credit-setting.key111')/*定时模式*/;
          break;
      }
      res.data.ruleTypeName = name;
      this.setState({ rulesGroup: res.data })
    }).catch(e => {
      errorMessage(e.response);
    })
  };

  getList = ruleCondition => {
    const { page, size, searchParams } = this.state;
    this.setState({ loading: true });
    let extraParams = { page, size };
    if(ruleCondition){
      extraParams.ruleCondition = ruleCondition;
    }
    creditModelService.getCreditRules(this.setId, Object.assign({}, searchParams, extraParams)).then(res => {
      let data = res.data;
      data.map((item, index) => {
        item.index = page * size + index + 1;
      });
      this.setState({
        data,
        loading: false,
        pagination: {
          total: Number(res.headers['x-total-count']),
          onChange: this.onChangePager,
          current: page + 1
        }
      })
    }).catch(e => {
      errorMessage(e.response);
      this.setState({ loading: false });
    })
  };

  //分页点击
  onChangePager = (page) => {
    if(page - 1 !== this.state.page)
      this.setState({page: page - 1}, this.getList)
  };

  handleNew = () => {
    this.setState({
      showSlideFrame: true,
      nowData: {}
    })
  };

  handleEdit = record => {
    this.setState({
      showSlideFrame: true,
      nowData: record
    })
  };

  handleCloseFrame = flag => {
    this.setState({ showSlideFrame: false });
    if(flag){
      this.getList()
    }
  };

  handleRowClick = record => {
    this.setState({
      showSlideFrame: true,
      nowData: record
    })
  };

  handleSearch = value => {
    this.setState({ page: 0 }, () => this.getList(value))
  };

  render() {
    const { infoList, pagination, columns, data, showSlideFrame, nowData, loading, saving, rulesGroup, updateState } = this.state;
    return (
      <div>
        <BasicInfo infoList={infoList}
                   infoData={rulesGroup}
                   loading={saving}
                   updateState={updateState}
                   updateHandle={this.handleUpdateRulesGroup}/>
        <div className="table-header">
          <div className="table-header-title">{messages('common.total',{total:`${pagination.total}`})}</div>  {/*共搜索到*条数据*/}
          <div className="table-header-buttons">
            <Button type="primary" onClick={this.handleNew}>{messages('common.create')}</Button>
          </div>
          <Search className="input-search"
                  placeholder={messages('credit-setting.key48')/*请输入规则项*/}
                  style={{
                    position: 'absolute',
                    right: 0,
                    bottom: 0,
                    width: 200
                  }}
                  onChange={(e) => this.handleSearch(e.target.value)} />
        </div>
        <ResizeTable
          columns={columns}
          size="middle"
          bordered
          rowKey="id"
          dataSource={data}
          pagination={pagination}
          loading={loading}
          onRow={record => ({
            onClick: () => this.handleRowClick(record)
          })}/>
        <div style={{fontSize: 14,margin: '20px 0',}}>
          <a onClick={this.handleBack}><Icon type="rollback" />{messages("common.back")/*返回*/}</a>
        </div>
        <SlideFrame show={showSlideFrame}
                    title={nowData.id ? messages('credit-setting.key49')/*编辑规则*/ : messages('credit-setting.key50')/*新增规则*/}
                    params={{
                      showSlideFrame,
                      nowData,
                      setId: this.setId,
                      ruleTypeId: rulesGroup.ruleTypeId
                    }}
                    onClose={() => this.setState({ showSlideFrame: false })}
                    content={NewCreditModelRule}
                    afterClose={this.handleCloseFrame}/>
      </div>
    )
  }
}

CreditModelRules.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    user: state.login.user,
    company: state.login.company,
    creditModel: state.creditSetting.creditModel
  }
}

export default connect(mapStateToProps)(CreditModelRules)
